// 样式配置
const buttonStyle = {
  background: '#409EFF',
  color: '#fff',
  padding: '9px 15px',
  'font-size': '12px',
  'border-radius': '4px',
  border: '1px solid #409EFF',
  cursor: 'pointer',
  margin: '10px 0',
  'z-index': '99999',
  position: 'fixed',
  display: 'block'
};

// 文件名消毒
const sanitizeFilename = (name) => 
  name.replace(/[/\\?%*:|"<>]/g, '-').replace(/\s+/g, ' ').trim();

// 创建下载按钮
function createDownloadButton(video) {
  const btn = document.createElement('button');
  Object.assign(btn.style, buttonStyle);
  btn.textContent = '下载视频';

  btn.onclick = () => {
    const sources = video.src || Array.from(video.querySelectorAll('source'))
      .map(s => s.src)
      .find(s => s);
    
    if (!sources) {
      console.log('未找到视频源');
      return;
    }

    const ext = sources.split('.').pop().split(/[?#]/)[0];
    const filename = `${sanitizeFilename(document.title)}.${ext}`;

    chrome.runtime.sendMessage({
      action: 'download',
      url: sources,
      filename: filename
    });
  };

  return btn;
}

// 优化容器布局
function adjustContainer(video, button) {
  const container = video.parentElement;
  const originalDisplay = container.style.display;
  
  container.style.display = 'block';
  container.style.overflow = 'visible';
  container.style.position = 'relative';
  
  const videoHeight = video.offsetHeight;
  container.style.minHeight = `${videoHeight + button.offsetHeight + 20}px`;
}

// 主函数
function init() {
  const processVideo = (video) => {
    if (video.dataset.downloadBtnAdded) return;
    
    const btn = createDownloadButton(video);
    video.insertAdjacentElement('afterend', btn);
    // adjustContainer(video, btn);

    video.dataset.downloadBtnAdded = true;
  };

  // 初始处理
  document.querySelectorAll('video').forEach(processVideo);

  // 动态监听
  new MutationObserver(mutations => {
    mutations.flatMap(m => Array.from(m.addedNodes))
      .forEach(node => {
        if (node.nodeName === 'VIDEO') processVideo(node);
        if (node.querySelectorAll) node.querySelectorAll('video').forEach(processVideo);
      });
  }).observe(document, { subtree: true, childList: true });
}

// 延迟初始化以避免布局未完成
// window.addEventListener('load', init, { once: true });
init();	// 代码里虽然是立即执行, 但插件最好设置成点击才执行, 否则有广告视频时就不会下载到真正视频
